//
//  SettingTableViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/24.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "SettingTableViewController.h"
#import "NavBarView.h"
#import "MainNavigationController.h"
#import "JKBrowserViewController.h"
#import "SDWebImageManager.h"
#import "JKProgressHUD.h"
#import "MeInSettingViewController.h"
#import "JKAccountManager.h"
#import "JKLoginTool.h"
#import "JKImageBrowserView.h"
#import "DonateViewController.h"

@interface SettingTableViewController ()

/** 自定义导航栏 */
@property (nonatomic, weak) NavBarView *navBarView;

/** 自动离线下载开关 */
@property (weak, nonatomic) IBOutlet UISwitch *autoDownloadSwitch;

/** 摇一摇夜间模式开关 */
@property (weak, nonatomic) IBOutlet UISwitch *shakeToChangeSkinSwitch;

/** 移动网络不下载图片开关 */
@property (weak, nonatomic) IBOutlet UISwitch *noImageWithouWifiSwitch;

/** 关闭阅读位置提示开关 */
@property (weak, nonatomic) IBOutlet UISwitch *readPositionNoticeOffSwitch;

/** 推送消息开关 */
@property (weak, nonatomic) IBOutlet UISwitch *pushMessageSwitch;

/** 用户头像 */
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;

/** 用户名 */
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;

/** 缓存大小label */
@property (weak, nonatomic) IBOutlet UILabel *cacheSizeLabel;

/** 旋转菊花 */
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorView;

/** 文件大小 */
@property (nonatomic, assign) CGFloat size;
@end

@implementation SettingTableViewController

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    // 更新头像和用户名
    [self updateUserIconAndName];
    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self updateSkin];
    [self.tableView bringSubviewToFront:self.navBarView];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(JKNavBarHeight - 10, 0, 0, 0);
    
    NavBarView *navBarView = [NavBarView barViewWithTitle:@"设置" showBackTitle:NO];
    navBarView.y = -JKNavBarHeight + 10;
    [self.tableView addSubview:navBarView];
    self.navBarView = navBarView;
    navBarView.backBtnClickBlock = nil;
    __weak typeof(self) weakSelf = self;
    [navBarView setBackBtnClickBlock:^(UIButton *btn) {
        MainNavigationController *mainNav = (MainNavigationController *)weakSelf.navigationController;
        !mainNav.backBtnBlock ? : mainNav.backBtnBlock();
    }];
    
    // 初始化所有开关
    [self setupSwitches];
    
    // 更新头像和用户名
    [self updateUserIconAndName];
    
    // 获取缓存大小
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.size = [SDImageCache sharedImageCache].getSize / 1024.0 / 1024;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.cacheSizeLabel.text = [NSString stringWithFormat:@"(已使用%.2fMB)", self.size];
            self.cacheSizeLabel.hidden = NO;
            [self.indicatorView stopAnimating];
        });
    });
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey] isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        
        cell.backgroundColor = JKColor(53, 53, 53);
        [self searchLabelInView:cell color:JKColor(160, 160, 160)];
        
    }else{ // 日间模式
        
        cell.backgroundColor = [UIColor whiteColor];
        [self searchLabelInView:cell color:[UIColor blackColor]];
    }
    
    return cell;
}

- (void)setupSwitches{
    self.autoDownloadSwitch.onTintColor = JKMainColor;
    self.shakeToChangeSkinSwitch.onTintColor = self.autoDownloadSwitch.onTintColor;
    self.noImageWithouWifiSwitch.onTintColor = self.autoDownloadSwitch.onTintColor;
    self.readPositionNoticeOffSwitch.onTintColor = self.autoDownloadSwitch.onTintColor;
    self.pushMessageSwitch.onTintColor = self.autoDownloadSwitch.onTintColor;
    
    self.autoDownloadSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:JKAutoDownloadKey];
    self.shakeToChangeSkinSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:JKIsShakeCanChangeSkinKey];
    self.readPositionNoticeOffSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:JKReadPositionNoticeOffKey];
    
    self.autoDownloadSwitch.enabled = NO;
    self.noImageWithouWifiSwitch.enabled = NO;
    self.pushMessageSwitch.enabled = NO;
}

// 更新用户名和头像
- (void)updateUserIconAndName{
    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:JKUserNameKey];
    self.userNameLabel.text = name;
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:JKIsLoginKey]) {
        self.iconImageView.image = [[UIImage imageNamed:@"Setting_Avatar"] circleImage];
        return;
    }
    
    NSString *imgPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"userIcon.png"];
    UIImage *img = [UIImage imageWithContentsOfFile:imgPath];
    if (img == nil) {
        img = [UIImage imageNamed:@"myIcon"];
    }
    self.iconImageView.image = [img circleImage];
}

// 自动离线下载开关
- (IBAction)autoDownloadSwitchClick:(UISwitch *)sender {
    [[NSUserDefaults standardUserDefaults] setObject:@(sender.isOn)forKey:JKAutoDownloadKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

// 摇一摇夜间模式
- (IBAction)shakeToChangeSkinSwitchClick:(UISwitch *)sender {
    [[NSUserDefaults standardUserDefaults] setObject:@(sender.isOn)forKey:JKIsShakeCanChangeSkinKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/** 阅读位置提示开关 */
- (IBAction)readPositionNoticeOffSwitch:(UISwitch *)sender {
    [[NSUserDefaults standardUserDefaults] setObject:@(sender.isOn)forKey:JKReadPositionNoticeOffKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        
        [self searchCellInView:self.tableView color:JKColor(53, 53, 53)];
        [self searchLabelInView:self.tableView color:JKColor(160, 160, 160)];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        [self.navBarView changeToDaySkin];
        
        [self searchCellInView:self.tableView color:[UIColor whiteColor]];
        [self searchLabelInView:self.tableView color:[UIColor blackColor]];
    }
}

//递归查找cell
- (void)searchCellInView:(UIView *)superView color:(UIColor *)bgColor{
    for (UIView *subview in superView.subviews) {
        
        //如果是UITableViewCell，设置背景颜色
        if ([subview isKindOfClass:[UITableViewCell class]]) {
            
            subview.backgroundColor = bgColor;
        }
        
        //继续查找子控件
        [self searchCellInView:subview color:bgColor];
    }
}

//递归查找UILabel
- (void)searchLabelInView:(UIView *)superView color:(UIColor *)textColor{
    for (UILabel *subview in superView.subviews) {
        
        //如果是UILabel，设置字体颜色
        if ([subview isKindOfClass:[UILabel class]]) {
            
            if ([subview.text isEqualToString:@"设置"]) {
                continue;
            }
            
            if ([subview.text containsString:@"Wi-Fi"]) {
                continue;
            }
            
            subview.textColor = textColor;
        }
        
        //继续查找子控件
        [self searchLabelInView:subview color:textColor];
    }
}

- (void)getSize{
    //图片缓存，SDWebImage默认并没有减去子文件夹本身的大小
    //我觉得也没必要减去，因为子文件也是属于整个缓存的一部分
    //NSUInteger size = [SDImageCache sharedImageCache].getSize;
    //JKLog(@"SDImageSize===%lu", (unsigned long)size);
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *caches= [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *cachePath = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"];
    
    //文件遍历器
    NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:cachePath];
    //文件夹中所有文件的总大小
    NSInteger totalSize = 0;
    for (NSString *fileName in fileEnumerator) {
        
        //每个文件的全路径
        NSString *filePath = [cachePath stringByAppendingPathComponent:fileName];
        
        //每个文件的详情
        NSDictionary *fileInfo = [manager attributesOfItemAtPath:filePath error:nil];
        
        /**判断文件类型：文件\文件夹，还可判断文件是否存在
         BOOL isDirectory = NO;
         [manager fileExistsAtPath:filePath isDirectory:&isDirectory];
         //如果是文件夹，跳过
         if (isDirectory) continue;*/
        
        //fileManager本身也有判断文件夹类型的NSFileType
        //NSFileTypeRegular   文件
        //NSFileTypeDirectory 文件夹
        if ([fileInfo[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
        
        //每个文件的大小
        NSInteger fileSize = [fileInfo[NSFileSize] integerValue];
        
        //将每个文件的大小加起来
        totalSize += fileSize;
    }
    JKLog(@"totalSize--%ld", totalSize);
}

#pragma mark - <UITableViewDelagate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 4) {
        [self performSegueWithIdentifier:@"donate" sender:nil];
//        JKBrowserViewController *browserVc = [[JKBrowserViewController alloc] init];
//        browserVc.request = [NSURLRequest requestWithURL:[NSURL URLWithString:JKMyGitUrl]];
//        [self.navigationController pushViewController:browserVc animated:YES];
        
    }else if (indexPath.section == 5) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"即将清除所有缓存及图片" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil]];
        [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
            [JKProgressHUD showWithStatus:@"正在清理..."];
            //清除缓存
            //使用NSFileManager
            //[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
            
            //使用SDImageCache
            [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                self.cacheSizeLabel.hidden = YES;
                [JKProgressHUD showSuccessWithStatus:@"清理缓存成功！"];
            }];
        }]];
        
        [self presentViewController:alertVc animated:YES completion:nil];
        
    }else if (indexPath.section == 0) { //
        if (![JKAccountManager sharedmanager].isLogin) {
            [JKLoginTool showLogin];
            return;
        }
        MeInSettingViewController *meVc = [[MeInSettingViewController alloc] init];
        meVc.isSettingIn = YES;
        [self.navigationController pushViewController:meVc animated:YES];
        
    }else if (indexPath.section == 7) {
        NSString *imageUrl = [[NSUserDefaults standardUserDefaults] objectForKey:JKLaunchImageUrlKey];
        
        if (!imageUrl) {
            [JKImageBrowserView showWithImage:[UIImage imageNamed:@"launch_img_bak.jpg"]];
            [JKProgressHUD showErrorWithStatus:@"啊哦，启动图api又更新了，等我查到之后再更新吧。"];
            return;
        }
        
        UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:imageUrl];
        
        if (!image) {
            [JKImageBrowserView showWithImageUrlStr:imageUrl];
            return;
        }
        
        [JKImageBrowserView showWithImage:image];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.navBarView.y = - JKNavBarHeight + 10 + (scrollView.contentOffset.y + JKNavBarHeight - 10);
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
